<template>
  <div class="event-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>事件管理</span>
          <div class="header-controls">
            <el-select v-model="selectedDevice" placeholder="选择设备" @change="onDeviceChange">
              <el-option
                v-for="device in devices"
                :key="device.id"
                :label="device.name"
                :value="device.id"
              />
            </el-select>
            <el-button type="primary" @click="refreshEvents">
              刷新事件
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 事件订阅管理 -->
      <div class="subscription-management">
        <el-card class="subscription-card">
          <template #header>
            <span>事件订阅管理</span>
          </template>
          <div class="subscription-controls">
            <div class="subscription-status">
              <el-tag 
                :type="subscriptionStatus ? 'success' : 'danger'"
                effect="dark"
                size="large"
              >
                {{ subscriptionStatus ? '已订阅' : '未订阅' }}
              </el-tag>
            </div>
            <div class="subscription-buttons">
              <el-button 
                type="success" 
                :disabled="!selectedDevice || subscriptionStatus"
                @click="subscribeEvents"
              >
                订阅事件
              </el-button>
              <el-button 
                type="danger" 
                :disabled="!selectedDevice || !subscriptionStatus"
                @click="unsubscribeEvents"
              >
                取消订阅
              </el-button>
            </div>
          </div>
          
          <!-- 事件类型配置 -->
          <div class="event-types-config">
            <h4>事件类型配置</h4>
            <el-checkbox-group v-model="selectedEventTypes">
              <el-checkbox 
                v-for="eventType in availableEventTypes" 
                :key="eventType.value"
                :label="eventType.value"
              >
                {{ eventType.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-card>
      </div>
      
      <!-- 查询条件 -->
      <div class="search-filters">
        <el-form :model="searchForm" inline>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="事件类型">
            <el-select v-model="searchForm.eventType" placeholder="选择事件类型">
              <el-option label="全部" value="" />
              <el-option 
                v-for="eventType in availableEventTypes" 
                :key="eventType.value"
                :label="eventType.label"
                :value="eventType.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="事件级别">
            <el-select v-model="searchForm.level" placeholder="选择事件级别">
              <el-option label="全部" value="" />
              <el-option label="信息" value="info" />
              <el-option label="警告" value="warning" />
              <el-option label="错误" value="error" />
              <el-option label="严重" value="critical" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchEvents">
              查询
            </el-button>
            <el-button @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 实时事件监控 -->
      <div class="real-time-events" v-if="subscriptionStatus">
        <el-card class="realtime-card">
          <template #header>
            <div class="realtime-header">
              <span>实时事件监控</span>
              <el-switch 
                v-model="realtimeEnabled"
                active-text="开启"
                inactive-text="关闭"
                @change="toggleRealtime"
              />
            </div>
          </template>
          <div class="realtime-events-list" v-if="realtimeEnabled">
            <div 
              v-for="event in realtimeEvents" 
              :key="event.id"
              class="realtime-event-item"
              :class="`level-${event.level}`"
            >
              <div class="event-time">{{ formatDateTime(event.timestamp) }}</div>
              <div class="event-content">
                <el-tag :type="getEventLevelColor(event.level)" size="small">
                  {{ getEventLevelText(event.level) }}
                </el-tag>
                <span class="event-type">{{ getEventTypeText(event.type) }}</span>
                <span class="event-message">{{ event.message }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 事件列表 -->
      <div class="event-list">
        <el-table 
          :data="events" 
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="timestamp" label="时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="事件类型" width="150">
            <template #default="{ row }">
              {{ getEventTypeText(row.type) }}
            </template>
          </el-table-column>
          <el-table-column prop="level" label="级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getEventLevelColor(row.level)">
                {{ getEventLevelText(row.level) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="source" label="事件源" width="150" />
          <el-table-column prop="message" label="事件描述" min-width="200" />
          <el-table-column prop="details" label="详细信息" width="120">
            <template #default="{ row }">
              <el-button size="small" @click="showEventDetails(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="acknowledgeEvent(row)" v-if="!row.acknowledged">
                确认
              </el-button>
              <el-button size="small" type="danger" @click="deleteEvent(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 批量操作 -->
        <div class="batch-operations" v-if="selectedEvents.length > 0">
          <el-alert
            :title="`已选择 ${selectedEvents.length} 个事件`"
            type="info"
            show-icon
            :closable="false"
          />
          <div class="batch-buttons">
            <el-button type="primary" @click="batchAcknowledge">
              批量确认
            </el-button>
            <el-button type="danger" @click="batchDelete">
              批量删除
            </el-button>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 事件详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="事件详情" 
      width="60%"
    >
      <div class="event-details" v-if="selectedEvent">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="事件ID">{{ selectedEvent.id }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ formatDateTime(selectedEvent.timestamp) }}</el-descriptions-item>
          <el-descriptions-item label="事件类型">{{ getEventTypeText(selectedEvent.type) }}</el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getEventLevelColor(selectedEvent.level)">
              {{ getEventLevelText(selectedEvent.level) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="事件源">{{ selectedEvent.source }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedEvent.acknowledged ? 'success' : 'warning'">
              {{ selectedEvent.acknowledged ? '已确认' : '未确认' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="事件描述" :span="2">{{ selectedEvent.message }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="event-raw-data" v-if="selectedEvent.rawData">
          <h4>原始数据</h4>
          <el-input
            type="textarea"
            :rows="10"
            :value="JSON.stringify(selectedEvent.rawData, null, 2)"
            readonly
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getEvents, 
  subscribeDeviceEvents, 
  unsubscribeDeviceEvents,
  acknowledgeEvent as apiAcknowledgeEvent,
  deleteEvent as apiDeleteEvent
} from '@/api/event'
import { getDevices } from '@/api/device'

const loading = ref(false)
const selectedDevice = ref('')
const subscriptionStatus = ref(false)
const realtimeEnabled = ref(false)
const detailDialogVisible = ref(false)
const selectedEvent = ref(null)

const devices = ref([])
const events = ref([])
const realtimeEvents = ref([])
const selectedEvents = ref([])

const selectedEventTypes = ref([])
const availableEventTypes = ref([
  { label: '运动检测', value: 'motion_detection' },
  { label: '视频丢失', value: 'video_loss' },
  { label: '音频检测', value: 'audio_detection' },
  { label: '篡改检测', value: 'tampering_detection' },
  { label: '存储异常', value: 'storage_failure' },
  { label: '网络异常', value: 'network_failure' },
  { label: '设备重启', value: 'device_reboot' },
  { label: '系统错误', value: 'system_error' }
])

const searchForm = reactive({
  startTime: '',
  endTime: '',
  eventType: '',
  level: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

let eventSocket = null

// 加载设备列表
const loadDevices = async () => {
  try {
    const response = await getDevices()
    devices.value = response.data.content || []
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
}

// 设备变化处理
const onDeviceChange = () => {
  subscriptionStatus.value = false
  realtimeEnabled.value = false
  events.value = []
  realtimeEvents.value = []
  
  if (selectedDevice.value) {
    loadEvents()
  }
}

// 加载事件列表
const loadEvents = async () => {
  if (!selectedDevice.value) return
  
  loading.value = true
  try {
    const params = {
      deviceId: selectedDevice.value,
      page: pagination.page - 1,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await getEvents(params)
    events.value = response.data.content || []
    pagination.total = response.data.totalElements || 0
  } catch (error) {
    ElMessage.error('加载事件列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新事件
const refreshEvents = () => {
  loadEvents()
}

// 搜索事件
const searchEvents = () => {
  pagination.page = 1
  loadEvents()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    startTime: '',
    endTime: '',
    eventType: '',
    level: ''
  })
  searchEvents()
}

// 订阅事件
const subscribeEvents = async () => {
  try {
    await subscribeDeviceEvents(selectedDevice.value, {
      eventTypes: selectedEventTypes.value
    })
    subscriptionStatus.value = true
    ElMessage.success('事件订阅成功')
  } catch (error) {
    ElMessage.error('事件订阅失败')
  }
}

// 取消订阅事件
const unsubscribeEvents = async () => {
  try {
    await unsubscribeDeviceEvents(selectedDevice.value)
    subscriptionStatus.value = false
    realtimeEnabled.value = false
    disconnectEventSocket()
    ElMessage.success('取消订阅成功')
  } catch (error) {
    ElMessage.error('取消订阅失败')
  }
}

// 切换实时监控
const toggleRealtime = (enabled) => {
  if (enabled) {
    connectEventSocket()
  } else {
    disconnectEventSocket()
  }
}

// 连接事件WebSocket
const connectEventSocket = () => {
  if (!selectedDevice.value) return
  
  const wsUrl = `ws://localhost:8080/ws/events/${selectedDevice.value}`
  eventSocket = new WebSocket(wsUrl)
  
  eventSocket.onopen = () => {
    console.log('事件WebSocket连接成功')
  }
  
  eventSocket.onmessage = (event) => {
    try {
      const eventData = JSON.parse(event.data)
      realtimeEvents.value.unshift(eventData)
      
      // 保持最新的50条实时事件
      if (realtimeEvents.value.length > 50) {
        realtimeEvents.value = realtimeEvents.value.slice(0, 50)
      }
      
      // 刷新事件列表
      loadEvents()
    } catch (error) {
      console.error('解析事件数据失败:', error)
    }
  }
  
  eventSocket.onerror = (error) => {
    console.error('事件WebSocket错误:', error)
    ElMessage.error('实时事件连接失败')
  }
  
  eventSocket.onclose = () => {
    console.log('事件WebSocket连接关闭')
  }
}

// 断开事件WebSocket
const disconnectEventSocket = () => {
  if (eventSocket) {
    eventSocket.close()
    eventSocket = null
  }
}

// 显示事件详情
const showEventDetails = (event) => {
  selectedEvent.value = event
  detailDialogVisible.value = true
}

// 确认事件
const acknowledgeEvent = async (event) => {
  try {
    await apiAcknowledgeEvent(event.id)
    ElMessage.success('事件确认成功')
    loadEvents()
  } catch (error) {
    ElMessage.error('事件确认失败')
  }
}

// 删除事件
const deleteEvent = async (event) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除此事件吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await apiDeleteEvent(event.id)
    ElMessage.success('删除成功')
    loadEvents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedEvents.value = selection
}

// 批量确认
const batchAcknowledge = async () => {
  try {
    for (const event of selectedEvents.value) {
      if (!event.acknowledged) {
        await apiAcknowledgeEvent(event.id)
      }
    }
    ElMessage.success('批量确认成功')
    loadEvents()
  } catch (error) {
    ElMessage.error('批量确认失败')
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedEvents.value.length} 个事件吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    for (const event of selectedEvents.value) {
      await apiDeleteEvent(event.id)
    }
    
    ElMessage.success('批量删除成功')
    loadEvents()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadEvents()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadEvents()
}

// 格式化函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

const getEventTypeText = (type) => {
  const eventType = availableEventTypes.value.find(t => t.value === type)
  return eventType ? eventType.label : type
}

const getEventLevelColor = (level) => {
  const colors = {
    info: 'primary',
    warning: 'warning',
    error: 'danger',
    critical: 'danger'
  }
  return colors[level] || 'info'
}

const getEventLevelText = (level) => {
  const texts = {
    info: '信息',
    warning: '警告',
    error: '错误',
    critical: '严重'
  }
  return texts[level] || level
}

onMounted(() => {
  loadDevices()
  // 默认选择所有事件类型
  selectedEventTypes.value = availableEventTypes.value.map(t => t.value)
})

onUnmounted(() => {
  disconnectEventSocket()
})
</script>

<style scoped>
.event-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.subscription-management {
  margin-bottom: 20px;
}

.subscription-card {
  background: #f8f9fa;
}

.subscription-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.subscription-buttons {
  display: flex;
  gap: 10px;
}

.event-types-config h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.search-filters {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.real-time-events {
  margin-bottom: 20px;
}

.realtime-card {
  background: #f0f9ff;
}

.realtime-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.realtime-events-list {
  max-height: 300px;
  overflow-y: auto;
}

.realtime-event-item {
  display: flex;
  gap: 10px;
  padding: 10px;
  border-bottom: 1px solid #e4e7ed;
  transition: background-color 0.3s;
}

.realtime-event-item:hover {
  background-color: #f5f7fa;
}

.realtime-event-item.level-critical {
  border-left: 4px solid #f56c6c;
}

.realtime-event-item.level-error {
  border-left: 4px solid #f56c6c;
}

.realtime-event-item.level-warning {
  border-left: 4px solid #e6a23c;
}

.realtime-event-item.level-info {
  border-left: 4px solid #409eff;
}

.event-time {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.event-content {
  flex: 1;
  display: flex;
  gap: 10px;
  align-items: center;
}

.event-type {
  font-weight: bold;
  color: #303133;
}

.event-message {
  color: #606266;
}

.event-list {
  margin-top: 20px;
}

.batch-operations {
  margin: 20px 0;
  padding: 15px;
  background: #f0f9ff;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.event-details {
  margin-top: 20px;
}

.event-raw-data {
  margin-top: 20px;
}

.event-raw-data h4 {
  margin: 0 0 10px 0;
  color: #333;
}
</style>